local desc_marm = [[ 
  # 山河图
  ______________________

  其实是草图。

]]

local HX = require "packages/huixiangkill/hxfs"

local marm_getLogic = function()
  local marm_logic = GameLogic:subclass("marm_logic")
   --关闭手杀特效
   function marm_logic:prepareForStart()
    local room = self.room
    self:addTriggerSkill(Fk.skills["game_rule"] --[[@as TriggerSkill]])
    for _, trig in ipairs(Fk.global_trigger) do
      if trig:getSkeleton().name ~= "mobile_effect" then
        self:addTriggerSkill(trig)
      end
    end
    for _, trig in ipairs(Fk.legacy_global_trigger) do
      self:addTriggerSkill(trig)
    end
    self.room:sendLog{ type = "$GameStart" }
  end

  -- function marm_logic:initialize(room)
  --   GameLogic.initialize(self, room)
  --   self.role_table = {
  --     nil,nil,nil,
  --     { "rebel", "rebel", "rebel", "rebel" },
  --   }
  -- end

  function marm_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local roles = self.role_table[n]
    table.shuffle(roles)

    local function getPlayerByScreenName(Room, name)
      return table.find(Room.players, function(p)
        return p._splayer:getScreenName() == name
      end)
    end
    local croom = room.room
    local cowner = croom:getOwner()
    local owner = getPlayerByScreenName(room, cowner:getScreenName())

    local level = {  --难度
      1, 2, 3, 4, 5, --普通
      6, 7, 8, 9, 10, --中等，该难度之后对局结束后保存玩家体力，即玩家不再回复体力
      11, 12, 13, 14, 15, --困难
      16, 17, 18, 19, 20, --噩梦
    }
    local save = {  --默认存档
      start = false, --剧本是否开始
      level = level[1], --难度，默认为普通1
      id = owner.id, --房主id
      player = owner, --房主本人
      glevel = 1, --武将等阶，默认为1阶，无加成；2阶体力上限+1；3阶初始手牌+1，出杀次数+1；4阶摸牌阶段摸牌数+1；5阶体力上限+1，获得“重生”（体力及手牌调整至5）
      gsave = { --武将的信息，其实史诗武将的初始手牌+1，手气卡+3……
        general = "", --武将
        hp = 4, --当前体力
        maxHp = 4, --体力上限
        shield = 0, --护甲
        draw = 0, --增加的摸牌数
        slash = 0, -- 增加的出杀次数
      },
      money = 0, --铜钱数
      equip = {  --已有装备
        [1] = "", --宝物
        [2] = "", --武器
        [3] = "", --防具
      },
      skill = {}, --已有技能
      project = { --初始战法，也包括已有战法
        C = {}, --普通
        B = {}, --稀有
        A = {}, --史诗
      },
    }
    local players = room.players
    local pname = owner._splayer:getScreenName()
    --[[TODO：读取存档部分
    local pdata = data.start
    --]]
    room:setBanner("marm_save", save)
    for _, p in ipairs(players) do
      if p.id == owner.id then
        room:setPlayerProperty(p, "role", "lord")
      else
        room:setPlayerProperty(p, "role", "rebel")
      end
      room:broadcastProperty(p, "role")
      room:setPlayerProperty(p, "role_shown", true)
    end

  end

  --- 分配座位
  function marm_logic:adjustSeats()
    local player_circle = {}
    local room = self.room
    room:setBanner("@[:]huixiangmode_rule","marm-intro") --模式简介
    local players = self.room.players
    local p = 1
    for i = 1, #players do
      if HX.Isyizhe(room, players[i]) then
        p = i
        break
      end
    end
    for j = p, #players do
      table.insert(player_circle, players[j])
    end
    for j = 1, p - 1 do
      table.insert(player_circle, players[j])
    end

    self.room:arrangeSeats(player_circle)
  end


  -- function marm_logic:prepareDrawPile()
  --   local room = self.room
  --   local allCardIds = Fk:getAllCardIds()
  --   local filterCardIds = {}
  --   --卡牌白名单
  --   local white_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token"}
  --   for i = #allCardIds, 1, -1 do
  --     local id = allCardIds[i]
  --     local card = Fk:getCardById(id)
  --     if card then
  --       if card.is_derived or not table.contains(white_cards, card.package.name) then
  --         table.removeOne(allCardIds, id)
  --         table.insert(room.void, id)
  --         room:setCardArea(id, Card.Void, nil)
  --       end
  --       if table.contains(white_cards, card.package.name) then
  --         if not card.is_derived then
  --           table.insert(filterCardIds, id)
  --         end
  --       end
  --     end
  --   end
  --   local seed = math.random(2 << 32 - 1)
  --   table.shuffle(filterCardIds, seed)
  --   room.draw_pile = filterCardIds
  --   for _, id in ipairs(room.draw_pile) do
  --     room:setCardArea(id, Card.DrawPile, nil)
  --   end
  --   room:doBroadcastNotify("PrepareDrawPile", seed)
  -- end

  function marm_logic:chooseGenerals()
    local room = self.room ---@type Room
    local generalNum = room.settings.generalNum
    local n = room.settings.enableDeputy and 2 or 1
    for _, p in ipairs(room.players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end

    local lord = room:getLord()
    if lord ~= nil then
      room:setCurrent(lord)
      local save = room:getBanner("marm_save")
      local players = room.players
      local target = table.filter(room.players, function(p) return p.id == save.id end)
      if save.gsave.general == "" then
        local generals = room:getNGenerals(generalNum * #target)
        local can_change = room:getBanner("changeGeneralNum") or generalNum --换将次数
        local all_cards = table.map(Fk:getGeneralsRandomly( can_change , Fk:getAllGenerals(), generals), Util.NameMapper)
        table.shuffle(all_cards)
        local data_table_true = {}
        for _, p in ipairs(target) do
          local arg = table.slice(generals, 1, can_change + 1)
          data_table_true[p.id] = {
            change = all_cards,
            cards = arg,  --generals
            num = n,  --n
            no_c = false, --no_convert
            heg = false, --heg
            type = "askForGeneralsChosen", --rule
            extra = {n = n}, --extra_data
          }
        end
        room:askToMiniGame(target, {
          skill_name = "AskForGeneral",
          game_type = "ChooseGeneralWithCanChange",
          data_table = data_table_true,
          timeout = self.room.settings.generalTimeout,
        })
        for _, p in ipairs(target) do
          local p_result = p.client_reply
          local general = p_result[1]
          local deputy = p_result[2]
          room:prepareGeneral(p, general, deputy)
        end
      else
        local general = save.gsave.general
        room:prepareGeneral(target[1], general)
      end
      for _, p in ipairs(room.players) do
        if not table.contains(target, p) then  -- TODO:按规则设置人机武将
          room:prepareGeneral(p, table.random(room.general_pile))
        end
      end
      room:askToChooseKingdom(players)
      for _, p in ipairs(players) do
        room:broadcastProperty(p, "general")
        room:broadcastProperty(p, "deputyGeneral")
      end
    else
      room:sendLog{type = "提示：你陷入了无法结束的对局，投降吧！", toast = true }
      local players = room.players
      lord = players[1]
      room:setCurrent(lord)
      local generals = table.random(room.general_pile, #room.players * generalNum)
      local req = Request:new(players, "AskForGeneral")
      for i, p in ipairs(players) do
        local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
        req:setData(p, { arg, n })
        req:setDefaultReply(p, table.random(arg, n))
      end
      for _, p in ipairs(players) do
        local result = req:getResult(p)
        local general, deputy = result[1], result[2]
        room:prepareGeneral(p, general, deputy)
      end

      room:askToChooseKingdom(players)
    end
    room:setTag("SkipNormalDeathProcess", true)
  end

  function marm_logic:attachSkillToPlayers()
    local room = self.room
    local players = room.players
    local n = room.settings.enableDeputy and 2 or 1
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: "..skillName.." doesn't exist!")
        return
      end
      if skill:hasTag(Skill.Lord) then return end
      -- if skill:hasTag(Skill.AttachedKingdom) and not
      -- table.contains(skill:getSkeleton().attached_kingdom, player.kingdom) then return end
      room:handleAddLoseSkills(player, skillName, nil, false,true)
      self:trigger(fk.EventAcquireSkill, player, {skill = skill, who = player})
    end
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(false)) do
        addRoleModSkills(p, s)
      end
      local deputy = Fk.generals[p.deputyGeneral]
      if deputy then
        for _, s in ipairs(deputy:getSkillNameList()) do
          addRoleModSkills(p, s)
        end
      end
    end
  end
  return marm_logic
end

local marm_mode = fk.CreateGameMode{
  name = "marm_mode",
  minPlayer = 2,
  maxPlayer = 8,
  rule = "#marm_rule&",
  logic = marm_getLogic,
  is_counted = function(self, room)
    return #room.players >= 2
  end,
  build_draw_pile = function(self)
    local allCardIds = Fk:getAllCardIds()
    local filterCardIds = {}
    local void = {}
    --卡牌白名单
    local white_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token"}
    for i = #allCardIds, 1, -1 do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived or not table.contains(white_cards, card.package.name) then
          table.removeOne(allCardIds, id)
          table.insert(void, id)
        end
        if table.contains(white_cards, card.package.name) then
          if not card.is_derived then
            table.insert(filterCardIds, id)
          end
        end
      end
    end
    return filterCardIds, void
  end,
  surrender_func = function(self, playedTime)
    return  { { text = "marm_surrender", passed = true } }
  end,
  winner_getter = function(self, victim)
    if not victim.surrendered and victim.rest > 0 then
      return ""
    end
    local room = victim.room
    local alive = table.filter(room.players, function(p)
      return not p.surrendered and not (p.dead and p.rest == 0)
    end)
    local winner = alive[1].role
    for _, p in ipairs(alive) do
      if p.role ~= winner then
        return ""
      end
    end
    return winner
  end,
  get_adjusted = function (self, player)
    local save = player.room:getBanner("marm_save")
    if save.level >= 6 and save.id == player.id then
      return {hp = save.gsave.hp, maxHp = save.gsave.maxHp, shield = save.gsave.shield}
    end
    return {}
  end,
}

Fk:loadTranslationTable{
  ["marm_mode"] = "丐版山河图",
  [":marm_mode"] = desc_marm,
  ["marm_surrender"] = "点击投降，重新挑战！",
  ["#marm_rule&"] = "山河图",
  ["marm-intro"] = "山河图",
  [":marm-intro"] = [[
  丐版山河图。
  ]],
}


return marm_mode
